const { verifyToken, decodeToken } =  require('./jwt.js')
const { Goods } = require('../model/goods')
const { goodsState } = require('../enum/state')

const loginGuard = (req, res, next) => {
    const token = req.headers.authorization
    console.log(req.url)
    console.log(req.url)
    // 不是登录、注册页面、不是商品详情接口/goods/:id
    if(req.url.indexOf('/login') === -1 && req.url.indexOf('/register') === -1 && req.url.indexOf('/goods') === -1 && req.url.indexOf('/date') === -1) {
        // 接口token验证,无token请求拦截
        // console.log('拦截请求1')
        const result = verifyToken(token)
        // console.log(result)
        if(result.code === 401) {
            // 验证失败
            res.status(401)
            res.json({
                message: result.message
            })
        } else {
            // 验证成功
            // 计算商品过期时间
            if (req.url.indexOf('goods') !== -1) {
              let overdueList = []
              let flag = 0
              Goods.find({state: goodsState.published}).then(list => {
                console.log('list', list)
                overdueList = list.filter(item => {
                  let endTime = new Date(item.createTime).getTime() + (item.duration * 24 * 60 * 60 * 1000)
                  const currentTime = new Date().getTime()
                  return endTime - currentTime < 0
                })
                console.log('overdueList', overdueList)
                if (overdueList.length > 0) {
                  overdueList.forEach(item => {
                    Goods.update({_id: item._id}, {state: goodsState.overdue}, (err, raw) => {
                      console.log('err', err)
                      console.log('raw', raw)
                      flag++
                      console.log(flag)
                      if (flag >= overdueList.length - 1) {
                        next()
                      }
                    })
                  })
                } else {
                  console.log('放行')
                  next()
                }
              })
            } else {
              next()
            }
        }
    } else {
        next()
    }
}
module.exports = loginGuard